<template>
  <div class="p-4">
    <h2 class="text-lg font-bold mb-2">SVG.js v3 矩形绘制 Demo</h2>

    <!-- SVG 容器 -->
    <div ref="canvasRef" class="border w-[600px] h-[400px] bg-gray-50"></div>

    <div class="mt-2 space-x-2">
      <button @click="addRectNoSelect" class="px-3 py-1 bg-blue-500 text-white rounded">
        添加矩形 (resize + drag，无外框)
      </button>
      <button @click="addRectWithSelect" class="px-3 py-1 bg-green-500 text-white rounded">
        添加矩形 (带 select 外框)
      </button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { SVG } from "@svgdotjs/svg.js";
import "@svgdotjs/svg.resize.js";
import "@svgdotjs/svg.draggable.js";
import "@svgdotjs/svg.select.js";

const canvasRef = ref(null);
const draw = ref(null);

onMounted(() => {
  draw.value = SVG().addTo(canvasRef.value).size("100%", "100%");
});

// 添加矩形 (无 select 外框)
const addRectNoSelect = () => {
  draw.value
    .rect(120, 80)
    .move(50, 50)
    .fill({ color: "rgba(239,76,76,0.1)" }) // ✅ 半透明红色
    .stroke({ color: "#ef4c4c", width: 2 })
    .select({ classRect: "custom-select-rect" })
    .resize()
    .draggable();
};

const addRectWithSelect = () => {
//   const rect = draw.value
//     .rect(120, 80)
//     .move(50, 50)
//     .fill({ color: "rgba(76, 175, 80, 0.2)" })
//     .stroke({ color: "#4caf50", width: 2 })
    
//     .draggable()  // 先让矩形可拖拽
//     .resize({ 
//         // 指定哪些手柄可用
//         handleSize: 8, 
//         preserveAspectRatio: false 
//     });  // 再让矩形可缩放

//   // 添加选框，显示蓝色边框
//   rect.select({ classRect: "custom-select-rect" });

  draw.value
  .rect(50, 50).fill("red").select()
  // 先移除通用的拖拽和缩放设置
  // 改为自定义交互逻辑
  .on('tap', (event) => {
    const shape = event.target;
    const bounds = shape.getBoundingClientRect();
    const margin = 10; // 边缘区域的宽度
    
    // 检查点击位置是否在边缘区域
    const isNearLeft = event.x < bounds.left + margin;
    const isNearRight = event.x > bounds.right - margin;
    const isNearTop = event.y < bounds.top + margin;
    const isNearBottom = event.y > bounds.bottom - margin;
    
    if (isNearLeft || isNearRight || isNearTop || isNearBottom) {
      // 边缘区域，启用缩放
      shape.resize({
        preserveAspectRatio: true,
        aroundCenter: true,
        grid: 10,
        degree: 0.1,
      });
    } else {
      // 中间区域，启用拖拽
      shape.draggable();
    }
  });
};
</script>

<style>
.custom-select-rect {
  fill: none !important;
  stroke: #2196f3 !important;
  stroke-width: 1 !important; 
}

/* 确保 resize 控制点可操作 */
.svgjs-resize-handle {
  fill: #2196f3 !important;       /* 控制点颜色 */
  pointer-events: all !important; /* 控制点可响应鼠标事件 */
  cursor: nwse-resize;
}
</style>
